package com.bangdao.app.jetpacktest.jetpack.databinding;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.bangdao.app.jetpacktest.BR;
import com.bangdao.app.jetpacktest.R;
import com.bangdao.app.jetpacktest.databinding.ActivityDataBindingBinding;
import com.bangdao.app.jetpacktest.databinding.ActivityDataBindingBindingImpl;
import com.bangdao.app.jetpacktest.databinding.ActivityMainBinding;
import com.bangdao.app.jetpacktest.jetpack.databinding.bean.Book;

public class DataBindingActivity extends AppCompatActivity {

    private ActivityDataBindingBinding binding;
    private Book book;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //之前的样子
        //setContentView(R.layout.activity_data_binding);
        //之后的样子
        binding = DataBindingUtil.setContentView(this, R.layout.activity_data_binding);
        //或者
//        binding = ActivityDataBindingBinding.inflate(getLayoutInflater());
//        setContentView(binding.getRoot());

        initData();
        initEvent();
    }

    /**
     * 赋值
     */
    private void initData() {
        book = new Book("Java编程思想", "大佬", 5);
        //第一种方式
        binding.setVariable(BR.book, book);
        //第二种方式
//        binding.setBook(book);
        //这种方式是不对的
//        binding.tvTitle.setText(book.getTitle());
//        binding.tvAuthor.setText(book.getAuthor());
//        binding.tvRating.setText(BookRatingUtil.getRatingString(book.getRating()));

    }

    private void initEvent() {
        binding.setEventHandler(new EventHandlerListener(this));
        //或者
//        binding.setVariable(BR.EventHandler, new EventHandlerListener(this));
        //这种方式是不对的
//        binding.btn1.setOnClickListener(v -> {
//            switch (v.getId()){
//                case R.id.btn1:
//                    Toast.makeText(DataBindingActivity.this, "点击了按钮1", Toast.LENGTH_SHORT).show();
//                    break;
//                case R.id.btn2:
//                    Toast.makeText(DataBindingActivity.this, "点击了按钮2", Toast.LENGTH_SHORT).show();
//                    break;
//            }
//        });
    }

    public class EventHandlerListener {
        private Context context;

        public EventHandlerListener(Context context) {
            this.context = context;
        }

        public void onButtonClicked(View view){
            switch (view.getId()){
                case R.id.btn1:
                    Toast.makeText(context, "点击了按钮1", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.btn2:
                    Toast.makeText(context, "点击了按钮2", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}